import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { Form, Button, Input, Space, message } from "antd";
import { useRequest, useUnmount } from "ahooks";
import * as APIS from "../../../constants/api-constants";
import axios from "axios";
import { REGISTER } from '../index'
import md5 from "md5";

import { USER_STATE } from '../../../constants/app-constants';
import "../style.css";

interface ShowProps {
  onPageStateChange: (pageState: string) => void;
}

interface Login {
  account: string;
  password: string;
}

const Login: React.FC<ShowProps> = ({ onPageStateChange }: ShowProps) => {
  const [form] = Form.useForm<Login>();
  const history = useHistory();
  const [dataUrl, setDataUrl] = useState<any>();
  let { loading, run, cancel } = useRequest(
    (data) => {
      const { account, password } = data;
      return {
        url: APIS.AUTHORTION,
        method: "POST",
        data: {
          account,
          password: md5(password),
        }
      }
    },
    {
      manual: true,
      onSuccess: (result) => {
        console.log(result);
        const { token, id, name, state, identity } = result.data.mainData;
        if (state === USER_STATE.FREEZE) {
          message.error("账号状态异常");
          form.resetFields();
          return;
        }
        if(state === USER_STATE.UNCHECK) {
          message.error("账号审核未通过");
          form.resetFields();
          return;
        }
        console.log("获取后台返回的登录信息", token);
        if (token) {
          // 添加全局请求头token
          localStorage.setItem("Authorization", token);
          localStorage.setItem("CurrentUserId", id);
          localStorage.setItem("identity",identity);
          localStorage.setItem("userName", name);

          axios.defaults.headers.common["Authorization"] = token;
          history.push("/home");
        }
      },
      onError: () => {
        // message.error('信息有误，请重新登录');
        console.log("onError");
      },
    }
  );
  useUnmount(() => {
    cancel();
  });

  useEffect(() => {
    axios.get(dataUrl)
      .then((result) => {
        const { token } = result.data.mainData;
        console.log("获取后台返回的登录信息", token);
        if (token) {
          // 添加全局请求头token
          localStorage.setItem("Authorization", token);
          axios.defaults.headers.common["Authorization"] = token;
          console.log(window.localStorage.getItem('identity'));
          history.push("/home");
        }
      })
  }, [dataUrl, history])

  // 游客模块
  const handleTouristLogin = (e: any) => {
    // console.log(e.currentTarget.getAttribute('data-url'));
    console.log(dataUrl);
    setDataUrl(e.currentTarget.getAttribute('data-url'));
    console.log(dataUrl);
  }

  return (
    <div className="index-box">
      <div className="index-inner-box">
        <div className="index-inner-left-box"></div>
        <div className="index-inner-middle-box">
          <div>
            <span id="info-span1">欢迎登录</span>
            <span id="info-span2">知识产权综合服务平台</span>
          </div>
          <span id="info-span3">
            Copyright&copy;天津国科医工科技发展有限公司,All Rights Reserved.
          </span>
        </div>
        <div className="index-inner-right-box">
          <span id="password-login-span">密码登录</span>
          <Form onFinish={(e) => run(e)} form={form}>
            <Form.Item
              name="account"
              rules={[{ message: "账号不能为空", required: true }]}
            >
              <Input placeholder="请输入您的账号" size="large"></Input>
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ message: "密码不能为空", required: true }]}
            >
              <Input
                placeholder="请输入登录密码"
                size="large"
                type="password"
              ></Input>
            </Form.Item>
            <Form.Item>
              <Button
                loading={loading}
                type="primary"
                size="large"
                block
                onClick={() => {
                  form.submit();
                }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          <div className="index-option">   
            <Button type="link" data-url={APIS.TOURIST} onClick={handleTouristLogin}>游客浏览</Button>
            <Space>
              <Button type="link">忘记密码</Button>
                <Button type="link" onClick={() => {
                  onPageStateChange(REGISTER);
                }}>免费注册</Button>
            </Space>
              
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
